<?php
/**
 * User: 五哥派
 * Date: 2024/6/30
 * Tel(同WX): 17335592719
 */

namespace app\admin\controller\store;

use app\admin\controller\Base;

use app\admin\model\store\Order as OrderModel;
use app\admin\model\store\OrderAddress as OrderAddressModel;
use app\admin\model\store\OrderItem as OrderItemModel;
use app\admin\model\system\Express as ExpressModel;
use app\admin\model\user\User as UserModel;
use app\admin\service\Order as OrderService;


use Exception;
use think\Db;
use think\exception\PDOException;

class Order extends Base{

    protected $model = null;
    protected $mOrderAddressModel = null;
    protected $mOrderItemModel = null;
    protected $mExpressModel = null;
    protected $mUserModel = null;

    public function __construct(OrderModel $model, OrderItemModel $mOrderItemModel, OrderAddressModel $mOrderAddressModel, ExpressModel $mExpressModel, UserModel $mUserModel){
        parent::__construct();
        $this->model = $model;
        $this->mOrderAddressModel = $mOrderAddressModel;
        $this->mOrderItemModel = $mOrderItemModel;
        $this->mExpressModel = $mExpressModel;
        $this->mUserModel = $mUserModel;
    }

    public function lst(){
        //订单数 售出商品数 订单金额
        //$order_num = db('store_order')->count();
        //$goods_num = db('store_order_item')->where('return_status', 0)->sum('num');
        //订单状态 0未付款,1已付款/待发货 2已发货/待收货 3已收货、待评价、已完成 -1退款、退款退货申请 -2已退款、已退款退货 -3拒绝 -4取消交易 -5关闭交易
        //$total_price = db('store_order')->where('order_status', 'in', '1,2,3,4,-3')->sum('total_price');

        //$this->assign('order_num',$order_num);
        //$this->assign('goods_num',$goods_num);
        //$this->assign('total_price',$total_price);
        return $this->fetch();
    }

    public function lstajax(){
        $where = [];
        $order_no = $this->request->param('order_no');
        if($order_no != ''){
            $where['order_no'] = $order_no;
        }
        //$title = input("get.title");
        //$where['title'] = array('like','%'.$title.'%');
        $list = $this->model->getList($where);
        $result = $list->toArray();
        return showLayui($result['total'], $result['data']);
    }

    //订单详情
    public function detail(){
        $id = input('id');//订单id
        $data = $this->model->findDataByID($id);
        $user = $this->mUserModel->findDataByID($data['user_id']);//下单用户
        $order_item = $this->mOrderItemModel->getList(['order_id' => $id]);
        $order_address = $this->mOrderAddressModel->findData(['order_id' => $id]);//下单用户
        //$user_money = $this->mUserMoneyModel->queryData(['order_id' => $id]);//查找佣金
        //$order_invoice = $this->mOrderInvoiceModel->findData(['order_id' => $id]);//发票信息
        //$order_return = $this->mOrderReturnModel->queryData(['order_id' => $id]);//售后信息

        $this->assign('data',$data);
        $this->assign('user',$user);
        $this->assign('order_item',$order_item);
        $this->assign('order_address',$order_address);
        //$this->assign('order_invoice',$order_invoice);
        //$this->assign('order_return',$order_return);
        //$this->assign('user_money',$user_money);

        return $this->fetch();
    }

    //去发货
    public function todelivery(){
        if(request()->isPost()){

            $data = request()->param();
            $express_no = $data['delivery_no'];
            $delivery_code = $data['delivery_code'];
            $expresst = Db::name('system_express')->where('code', $delivery_code)->find();
            $express_name = $expresst['name'];
            $time = time();
            $orderId = $data['id'];
            $order = [
                'id' => $orderId,
                'order_status' => 2,//已发货、待收货
                'delivery_status' => 1,//已发货
                'delivery_code' => $delivery_code,
                'delivery_name' => $express_name,
                'delivery_no' => $express_no,
                'delivery_time' => $time,
                'update_time' => $time,
                //'state' => 3
            ];
            /*
            //查询是否存在,如果存在绕过快递100订阅
            $is_express_no = $this->mExpressSubModel->where(['express_no' => $express_no])->count();
            // 订阅快递查询
            if ($is_express_no == 0) {
                $callbackUrl = config('secure.express_back_url');
                $returncode = Kd100::getInstance()->subScribe($delivery_code, $express_no, $callbackUrl);
                if ($returncode['returnCode'] != 200) {
                    return Show::error('快递订阅接口异常-'.$returncode['message']);
                }
                $express = [
                    'sign' => Kd100::getInstance()->sign($express_no),
                    'express_no' => $express_no,
                    'returncode' => $returncode['returnCode'],
                    'message' => $returncode['message']
                ];
            }*/
            // 推送消息
            //$this->pushOrder($id,'已发货');


            //短信通知
            Db::startTrans();
            try {
                $result = $this->model->saveData($order,true);
                // 写入快递订阅列表
                //if ($express) $this->mExpressSubModel->saveData($express, false);
                /*************************订单操作表 start ***************************************/
                Db::name('store_order_record')->insert([
                    'order_id' => $orderId,
                    'type' => 'delivery_goods',
                    //'change_message' => '新增配送信息 已发货 快递公司：'.$express_name.' 快递单号：'.$data['delivery_no'],
                    'msg' => '新增配送信息 已发货',
                    'create_time' => $time,
                    'update_time' => $time,
                ]);


                //上传小程序 发货信息录入
                $sOrderService = new OrderService();
                $sOrderService->shipping($orderId);

                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            // 判断是否支付成功
            if($result){
                return success('发货成功!');
            }else{
                return error('网络异常，发货失败!');
            }

        }

        $id = $this->request->param('id');
        $data = $this->model->findDataByID($id);
        $this->assign('data',$data);

        $expressList = $this->mExpressModel->queryData(['status' => 1]);
        $this->assign('expressList',$expressList);

        return $this->fetch();
    }


    //管理员备注
    public function note(){
        if(request()->isPost()){
            Db::startTrans();
            try{
                $data = request()->param();

                $time = time();
                $data['update_time'] = $time;
                $this->model->saveData($data,true);

                /*************************订单操作表 start ***************************************/
                db('store_order_record')->insert([
                    'order_id' => $data['id'],
                    'type' => 'update_admin_note',
                    'msg' => '修改管理员备注',
                    'create_time' => $time,
                    'update_time' => $time,
                ]);
                Db::commit();
                return success('保存成功!');
            }catch (Exception $ex){
                Db::rollback();
                return error('保存失败!');
            }

        }
        $id = $this->request->param('id');
        $data = $this->model->findDataByID($id);
        $this->assign('data',$data);

        return $this->fetch();
    }


    //已收货
    public function done(){
        $id = $this->request->param('id');

        $time = time();
        Db::startTrans();
        try{

            $data = [
                'id' => $id,
                'order_status' => 3,//已送达
                'receipt_status' => 1,//已收货
                'receipt_time' => $time,//送达时间
                'confirm_time' => $time,//确认订单时间
                'update_time' => $time
            ];
            $this->model->saveData($data,true);

            /*************************订单操作表 start ***************************************/
            db('store_order_record')->insert([
                'order_id' => $id,
                'type' => 'user_take_delivery',
                'msg' => '用户已收货',
                'create_time' => $time,
                'update_time' => $time,
            ]);

            Db::commit();
            return success('保存成功!');
        }catch (Exception $ex){
            Db::rollback();
            return error('保存失败!');
        }
    }




}




